package com.example.mediamoudle.viewpage.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.android.baselibrary.base.BaseActivity
import com.example.mediamoudle.R
import com.example.mediamoudle.databinding.ActivityViewPagerMainBinding
import com.example.mediamoudle.router.MediaRouterPath
import com.example.mediamoudle.utlis.MediaDataUtils
import com.example.mediamoudle.viewpage.adapter.ViewPagerMediaFragmentAdapter
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.cache.CacheFactory
import com.shuyu.gsyvideoplayer.player.PlayerFactory
import tv.danmaku.ijk.media.exo2.Exo2PlayerManager
import tv.danmaku.ijk.media.exo2.ExoPlayerCacheManager

@Route(path = MediaRouterPath.MEDIA_VIEWPAGER)
class ViewPagerMainActivity : BaseActivity<ActivityViewPagerMainBinding>() {
    override fun getLayoutId(): Int = R.layout.activity_view_pager_main

    override fun initView() {
       PlayerFactory.setPlayManager(Exo2PlayerManager::class.java)
        CacheFactory.setCacheManager( ExoPlayerCacheManager::class.java)
        val adapter = ViewPagerMediaFragmentAdapter(this)
        mBinding.viewPagerMedia.adapter = adapter
        mBinding.viewPagerMedia.offscreenPageLimit =3
        mBinding.viewPagerMedia.orientation = ViewPager2.ORIENTATION_VERTICAL
        adapter.setFragmentList(initFragment())
        initFragment()
    }

    private fun initFragment(): MutableList<Fragment> {
        val fragmentList = mutableListOf<Fragment>()
        MediaDataUtils.dataList.forEachIndexed { position,it->
             fragmentList.add(
                ARouter.getInstance().build(MediaRouterPath.MEDIA_VIEWPAGER_FRAGMENT)
                    .withInt("position",position)
                    .withString(MediaRouterPath.MEDIA_URL, it).navigation() as Fragment
            )
        }
        return fragmentList
    }

    override fun initListener() {

    }
    override fun onBackPressed() {
       if (GSYVideoManager.backFromWindowFull(this)) {
            return
       }
        super.onBackPressed()
    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
    }

    override fun onResume() {
        super.onResume()
       GSYVideoManager.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
    }
}